package com.jarvis.pzz.modules.shop;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.donkingliang.labels.LabelsView;
import com.jarvis.pzz.MainActivity;
import com.jarvis.pzz.R;
import com.jarvis.pzz.WebViewActivity;
import com.jarvis.pzz.common.AppStatus;
import com.jarvis.pzz.common.BaseFragment;
import com.jarvis.pzz.common.ResponseData;
import com.jarvis.pzz.models.AreaListModel;
import com.jarvis.pzz.models.BusinessAreaListModel;
import com.jarvis.pzz.models.CityModel;
import com.jarvis.pzz.models.MeasureAreaListModel;
import com.jarvis.pzz.models.PriceAreaListModel;
import com.jarvis.pzz.models.SearchTypeModel;
import com.jarvis.pzz.models.ShopListModel;
import com.jarvis.pzz.models.ShopsListByFilterModel;
import com.jarvis.pzz.models.ShopsSearchModel;
import com.jarvis.pzz.modules.shop.adapter.ShopAdapter;
import com.jarvis.pzz.modules.shop.adapter.ShopGridAdapter;
import com.jarvis.pzz.modules.shop.adapter.SignlLineAdapter;
import com.jarvis.pzz.modules.shop.view.MapActivity;
import com.jarvis.pzz.modules.shop.view.ScreenActivity;
import com.jarvis.pzz.modules.shop.view.ShopDetailsActivity;
import com.jarvis.pzz.seervers.RequestService;
import com.jarvis.pzz.util.DipUtil;
import com.jarvis.pzz.util.DividerGridItemDecoration;
import com.jarvis.pzz.util.DividerItemDecoration;
import com.jarvis.pzz.util.net.RequestApi;
import com.umeng.analytics.MobclickAgent;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;

/**
 * Created by jarvis.liu on 2016-11-02.
 */

public class ShopFragment extends BaseFragment implements View.OnClickListener, View.OnKeyListener {
    @BindView(R.id.title)
    RelativeLayout title;
    @BindView(R.id.rel_bg)
    RelativeLayout rel_bg;
    @BindView(R.id.rel_left)
    RelativeLayout rel_left;
    @BindView(R.id.rel_middle)
    RelativeLayout rel_middle;
    @BindView(R.id.tv_left)
    TextView tv_left;
    @BindView(R.id.labels)
    LabelsView labelsView;

    @BindView(R.id.lin_diag_area)
    LinearLayout lin_diag_area;
    @BindView(R.id.lin_dialog_measure)
    LinearLayout lin_dialog_measure;
    @BindView(R.id.lin_dialog_price)
    LinearLayout lin_dialog_price;
    @BindView(R.id.ed_search)
    EditText ed_search;

    @BindView(R.id.rel_area)
    RelativeLayout rel_area;
    @BindView(R.id.tv_area)
    TextView tv_area;
    @BindView(R.id.img_area)
    ImageView img_area;

    @BindView(R.id.rel_measure)
    RelativeLayout rel_measure;
    @BindView(R.id.tv_measure)
    TextView tv_measure;
    @BindView(R.id.img_measure)
    ImageView img_measure;

    @BindView(R.id.rel_price)
    RelativeLayout rel_price;
    @BindView(R.id.tv_price)
    TextView tv_price;
    @BindView(R.id.img_price)
    ImageView img_price;

    @BindView(R.id.lin_screen)
    LinearLayout lin_screen;

    @BindView(R.id.recy_area)
    RecyclerView recy_area;
    SignlLineAdapter areaAdapter;
    @BindView(R.id.recy_measure)
    RecyclerView recy_measure;
    SignlLineAdapter measureAdapter;
    @BindView(R.id.recy_price)
    RecyclerView recy_price;
    SignlLineAdapter priceAdapter;

    @BindView(R.id.recy_shop_grid)
    RecyclerView recy_shop_grid;
    @BindView(R.id.ptr_shop_grid)
    PtrClassicFrameLayout ptr_shop_grid;
    private ShopGridAdapter shopGridAdapter;

    @BindView(R.id.recy_shop)
    RecyclerView recy_shop;
    @BindView(R.id.ptr_shop)
    PtrClassicFrameLayout ptr_shop;

    @BindView(R.id.tv_area_left)
    TextView tv_area_left;
    @BindView(R.id.tv_busniss_left)
    TextView tv_busniss_left;
    private ShopAdapter shopAdapter;

    private int pageSize = 10;
    private int currentPage = 1;
    private int maxPage = 1;
    private boolean isClick = true;

    private boolean area_select;
    private boolean measure_select;
    private boolean price_select;

    private RequestService service;

    ShopsSearchModel shopsSearchModel;
    private String show_type = "list";

    private boolean isLoading = false;
    private int status = 0;


    public static ShopFragment newInstance() {
        Bundle args = new Bundle();
        ShopFragment fragment = new ShopFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_shop;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            System.out.println("un hidden:" + getClass().toString());
            status = 1;
            MobclickAgent.onPageStart(getClass().toString()); //统计页面，"MainScreen"为页面名称，可自定义
            MobclickAgent.onResume(getContext());
            tv_left.setText(AppStatus.getInstance().cityName);
            setStatusWhite(false);
            ed_search.setText(AppStatus.getInstance().value);
            AppStatus.getInstance().value="";
            if ("list".equals(show_type)) {
                ptr_shop.postDelayed(
                        new Runnable() {
                            @Override
                            public void run() {
                                ptr_shop.autoRefresh();
                            }
                        }, 100);
            } else {
                ptr_shop_grid.postDelayed(
                        new Runnable() {
                            @Override
                            public void run() {
                                ptr_shop_grid.autoRefresh();
                            }
                        }, 100);
            }
            setLabels();
        } else {
            System.out.println("hidden:" + getClass().toString());
            status = 2;
            MobclickAgent.onPageEnd(getClass().toString());
            MobclickAgent.onPause(getContext());
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        tv_left.setText(AppStatus.getInstance().cityName);
        setStatusWhite(false);
        ed_search.setText(AppStatus.getInstance().value);
        AppStatus.getInstance().value="";
        if (status == 0) {
            System.out.println("onResume:" + getClass().toString());
            MobclickAgent.onPageStart(getClass().toString()); //统计页面，"MainScreen"为页面名称，可自定义
            MobclickAgent.onResume(getContext());
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (status == 0) {
            System.out.println("onPause:" + getClass().toString());
            MobclickAgent.onPageEnd(getClass().toString());
            MobclickAgent.onPause(getContext());
        }
    }

    @Override
    public void initData() {
        if ("list".equals(show_type)) {
            ptr_shop.postDelayed(
                    new Runnable() {
                        @Override
                        public void run() {
                            ptr_shop.autoRefresh();
                        }
                    }, 100);
        } else {
            ptr_shop_grid.postDelayed(
                    new Runnable() {
                        @Override
                        public void run() {
                            ptr_shop_grid.autoRefresh();
                        }
                    }, 100);
        }
        tv_left.setText(AppStatus.getCityList().get(0).getCityName());
        setSelectData();
        setLabels();
    }

    public static boolean checkPermission(Context context, String permission) {
        boolean result = false;
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                Class<?> clazz = Class.forName("android.content.Context");
                Method method = clazz.getMethod("checkSelfPermission", String.class);
                int rest = (Integer) method.invoke(context, permission);
                if (rest == PackageManager.PERMISSION_GRANTED) {
                    result = true;
                } else {
                    result = false;
                }
            } catch (Exception e) {
                result = false;
            }
        } else {
            PackageManager pm = context.getPackageManager();
            if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
                result = true;
            }
        }
        return result;
    }

    public static String getDeviceInfo(Context context) {
        try {
            org.json.JSONObject json = new org.json.JSONObject();
            android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String device_id = null;
            if (checkPermission(context, Manifest.permission.READ_PHONE_STATE)) {
                device_id = tm.getDeviceId();
            }
            String mac = null;
            FileReader fstream = null;
            try {
                fstream = new FileReader("/sys/class/net/wlan0/address");
            } catch (FileNotFoundException e) {
                fstream = new FileReader("/sys/class/net/eth0/address");
            }
            BufferedReader in = null;
            if (fstream != null) {
                try {
                    in = new BufferedReader(fstream, 1024);
                    mac = in.readLine();
                } catch (IOException e) {
                } finally {
                    if (fstream != null) {
                        try {
                            fstream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            json.put("mac", mac);
            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }
            if (TextUtils.isEmpty(device_id)) {
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(),
                        android.provider.Settings.Secure.ANDROID_ID);
            }
            json.put("device_id", device_id);
            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void setSelectData() {
        showDialog("loading...");
        Call<ResponseData<ShopsSearchModel>> shopsSearchParams = service.getShopsSearchParams();
        shopsSearchParams.enqueue(new Callback<ResponseData<ShopsSearchModel>>() {
            @Override
            public void onResponse(Call<ResponseData<ShopsSearchModel>> call, Response<ResponseData<ShopsSearchModel>> response) {
                disMiss();
                if (response.body() != null) {
                    int resultCode = response.body().getResultCode();
                    if (resultCode == 200) {
                        shopsSearchModel = response.body().getData();
                        if (shopsSearchModel != null) {
                            setData();
                        }
                    } else {
                        showTextToast(response.body().getMessage());
                    }
                } else {
                    showTextToast("请求失败");
                }
            }

            @Override
            public void onFailure(Call<ResponseData<ShopsSearchModel>> call, Throwable t) {
                disMiss();
            }
        });
    }

    private void setData() {
        setAreaAdapter();
        setMeasureAdapter();
        setPriceAdapter();
    }

    private void setBar() {
        title.getBackground().setAlpha(255);
        int statusBarHeight1 = -1;
//获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
        }
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(title.getLayoutParams());
        lp.height= DipUtil.dip2px(getActivity(), 50)+statusBarHeight1;
        title.setLayoutParams(lp);
        title.setPadding(0, statusBarHeight1, 0, 0);
//        RelativeLayout.LayoutParams lps = new RelativeLayout.LayoutParams(rel_bg.getLayoutParams());
//        lps.height=lps.height+statusBarHeight1;
//        rel_bg.setLayoutParams(lps);

        //rel_bg.setPadding(0, statusBarHeight1, 0, 0);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
            case RESULT_OK:
                if ("list".equals(show_type)) {
                    ptr_shop.postDelayed(
                            new Runnable() {
                                @Override
                                public void run() {
                                    ptr_shop.autoRefresh();
                                }
                            }, 100);
                } else {
                    ptr_shop_grid.postDelayed(
                            new Runnable() {
                                @Override
                                public void run() {
                                    ptr_shop_grid.autoRefresh();
                                }
                            }, 100);
                }
                setLabels();
                break;
            default:
                break;
        }
    }

    @Override
    protected void initView() {
        service = RequestApi.create(RequestService.class);
        ed_search.setText(AppStatus.getInstance().value);
        AppStatus.getInstance().value="";
        setBar();
//        setStatus(false);
        setAdapter();
        setGridAdapter();
        setRefresh();
        setGridRefresh();
        setListener();
    }

    /**
     * 设置监听事件
     */
    public void setListener() {
        rel_area.setOnClickListener(this);
        rel_left.setOnClickListener(this);
        rel_measure.setOnClickListener(this);
        rel_price.setOnClickListener(this);
        lin_screen.setOnClickListener(this);
        ed_search.setOnKeyListener(this);
        tv_area_left.setOnClickListener(this);
        tv_busniss_left.setOnClickListener(this);
        recy_shop.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                ShopListModel shopListModel = shopAdapter.getData().get(i);
                if ("0".equals(shopListModel.getIsShop())) {
                    String advUrl = shopListModel.getAdvUrl();
                    Intent intent=new Intent(getActivity(), WebViewActivity.class);
                    intent.putExtra("type","0");
                    intent.putExtra("url",advUrl);
                    intent.putExtra("title",shopListModel.getAdvTitle());
                    startActivity(intent);
                }else {
                    String shopId = shopListModel.getShopId();
                    startActivity(new Intent(getActivity(), ShopDetailsActivity.class).putExtra("shopId", shopId));
                }

            }
        });
        recy_shop_grid.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                ShopListModel shopListModel = shopGridAdapter.getData().get(i);
                String shopId = shopListModel.getShopId();
                startActivity(new Intent(getActivity(), ShopDetailsActivity.class).putExtra("shopId", shopId));
            }

        });
        recy_area.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                SearchTypeModel searchTypeModel = areaAdapter.getData().get(i);
                reset();
                AddOrChangeData(searchTypeModel);
                setLabels();
                if ("list".equals(show_type)) {
                    ptr_shop.postDelayed(
                            new Runnable() {
                                @Override
                                public void run() {
                                    ptr_shop.autoRefresh();
                                }
                            }, 100);
                } else {
                    ptr_shop_grid.postDelayed(
                            new Runnable() {
                                @Override
                                public void run() {
                                    ptr_shop_grid.autoRefresh();
                                }
                            }, 100);
                }
            }
        });
        recy_measure.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                SearchTypeModel searchTypeModel = measureAdapter.getData().get(i);
                reset();
                AddOrChangeData(searchTypeModel);
                setLabels();
                if ("list".equals(show_type)) {
                    ptr_shop.postDelayed(
                            new Runnable() {
                                @Override
                                public void run() {
                                    ptr_shop.autoRefresh();
                                }
                            }, 100);
                } else {
                    ptr_shop_grid.postDelayed(
                            new Runnable() {
                                @Override
                                public void run() {
                                    ptr_shop_grid.autoRefresh();
                                }
                            }, 100);
                }
            }
        });
        recy_price.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                SearchTypeModel searchTypeModel = priceAdapter.getData().get(i);
                reset();
                AddOrChangeData(searchTypeModel);
                setLabels();
                if ("list".equals(show_type)) {
                    ptr_shop.postDelayed(
                            new Runnable() {
                                @Override
                                public void run() {
                                    ptr_shop.autoRefresh();
                                }
                            }, 100);
                } else {
                    ptr_shop_grid.postDelayed(
                            new Runnable() {
                                @Override
                                public void run() {
                                    ptr_shop_grid.autoRefresh();
                                }
                            }, 100);
                }
            }
        });

        labelsView.setOnLabelClickListener(new LabelsView.OnLabelClickListener() {
            @Override
            public void onLabelClick(View label, String labelText, int position) {
                //label是被点击的标签，labelText是标签的文字，position是标签的位置。
                if (!ptr_shop.isAutoRefresh() && !ptr_shop_grid.isAutoRefresh()) {
                    if ("list".equals(show_type)) {
                        ptr_shop.postDelayed(
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        ptr_shop.autoRefresh();
                                    }
                                }, 100);
                    } else {
                        ptr_shop_grid.postDelayed(
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        ptr_shop_grid.autoRefresh();
                                    }
                                }, 100);
                    }
                    AppStatus.getInstance().getList().remove(position);
                    setLabels();
                }
            }
        });
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_ENTER) {
            // 先隐藏键盘
            ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(getActivity().getCurrentFocus()
                            .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
            if ("list".equals(show_type)) {
                ptr_shop.postDelayed(
                        new Runnable() {
                            @Override
                            public void run() {
                                ptr_shop.autoRefresh();
                            }
                        }, 100);
            } else {
                ptr_shop_grid.postDelayed(
                        new Runnable() {
                            @Override
                            public void run() {
                                ptr_shop_grid.autoRefresh();
                            }
                        }, 100);
            }
            return true;
        } else {
            return false;
        }

    }

    private void AddOrChangeData(SearchTypeModel searchTypeModel) {
        boolean is_add = true;
        List<SearchTypeModel> list = AppStatus.getInstance().getList();
        for (int i = 0; i < list.size(); i++) {
            if (searchTypeModel.getType().equals(list.get(i).getType())) {
                is_add = false;
                list.set(i, searchTypeModel);
            }
        }
        if (is_add) {
            list.add(searchTypeModel);
        }
        AppStatus.getInstance().setList(list);
    }

    private void setLabels() {
        ArrayList<String> label = new ArrayList<>();
        for (int i = 0; i < AppStatus.getInstance().getList().size(); i++) {
            label.add(AppStatus.getInstance().getList().get(i).getDisplayValue());
        }
        if (label.size() == 0) {
            labelsView.setVisibility(View.GONE);
        } else {
            labelsView.setVisibility(View.VISIBLE);
            labelsView.setLabels(label); //直接设置一个字符串数组就可以了。
        }
    }

    /**
     * 设置下拉刷新
     */
    public void setRefresh() {
        ptr_shop.setMode(PtrFrameLayout.Mode.BOTH);
        ptr_shop.disableWhenHorizontalMove(true);
        ptr_shop.setLastUpdateTimeRelateObject(this);
        ptr_shop.setPtrHandler(new PtrDefaultHandler2() {

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return PtrDefaultHandler2.checkContentCanBePulledUp(frame, recy_shop, footer);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler2.checkContentCanBePulledDown(frame, recy_shop, header);
            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                pageSize=15;
                if (currentPage < maxPage) {
                    currentPage++;
                    loadListData();
                } else {
                    ptr_shop.refreshComplete();
                }
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                shopAdapter.setNewData(new ArrayList<ShopListModel>());
                currentPage = 1;
                pageSize=10;
                loadListData();
            }
        });
    }

    public void setGridRefresh() {
        ptr_shop_grid.setMode(PtrFrameLayout.Mode.BOTH);
        ptr_shop_grid.disableWhenHorizontalMove(true);
        ptr_shop_grid.setLastUpdateTimeRelateObject(this);
        ptr_shop_grid.setPtrHandler(new PtrDefaultHandler2() {

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return PtrDefaultHandler2.checkContentCanBePulledUp(frame, recy_shop_grid, footer);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler2.checkContentCanBePulledDown(frame, recy_shop_grid, header);
            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                if (currentPage < maxPage) {
                    currentPage++;
                    loadGridData();
                } else {
                    ptr_shop_grid.refreshComplete();
                }
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                shopGridAdapter.setNewData(new ArrayList<ShopListModel>());
                currentPage = 1;
                loadGridData();
            }
        });
    }

    private void loadListData() {
        String searchParam = ed_search.getText().toString();

        String areaId = "";
        String measureArea = "";
        String priceArea = "";
        String shopType = "";
        String shopSaleType = "";
        String shopRunIndustry = "";
        String shopLabelId = "";
        String businessArea = "";
        for (int i = 0; i < AppStatus.getInstance().getList().size(); i++) {
            SearchTypeModel searchTypeModel = AppStatus.getInstance().getList().get(i);
            if ("areaId".equals(searchTypeModel.getType())) {
                if(searchTypeModel.isIs_business()){
                    businessArea= searchTypeModel.getDisplayValue();
                }else {
                    areaId = searchTypeModel.getId();
                }
            } else if ("measureArea".equals(searchTypeModel.getType())) {
                measureArea = searchTypeModel.getId();
            } else if ("priceArea".equals(searchTypeModel.getType())) {
                priceArea = searchTypeModel.getId();
            } else if ("shopType".equals(searchTypeModel.getType())) {
                shopType = searchTypeModel.getId();
            } else if ("shopSaleType".equals(searchTypeModel.getType())) {
                shopSaleType = searchTypeModel.getId();
            } else if ("shopRunIndustry".equals(searchTypeModel.getType())) {
                shopRunIndustry = searchTypeModel.getId();
            } else if ("shopLabelId".equals(searchTypeModel.getType())) {
                shopLabelId = searchTypeModel.getId();
            }
        }
        Call<ResponseData<ShopsListByFilterModel>> shopsListByFilter = service.getShopsListByFilter(searchParam, areaId, measureArea, priceArea, shopType, shopSaleType, shopRunIndustry, shopLabelId, businessArea, currentPage, pageSize, AppStatus.getInstance().type);
        shopsListByFilter.enqueue(new Callback<ResponseData<ShopsListByFilterModel>>() {
            @Override
            public void onResponse(Call<ResponseData<ShopsListByFilterModel>> call, Response<ResponseData<ShopsListByFilterModel>> response) {
                ptr_shop.refreshComplete();
                System.out.println("55555");
                isLoading = false;
                if (response.body() != null) {
                    int total_count = response.body().getTotalcount();
                    int resultCode = response.body().getResultCode();
                    if (resultCode == 200) {
                        ShopsListByFilterModel shopsListByFilterModel = response.body().getData();
                        maxPage = total_count % pageSize == 0 ? total_count / pageSize : total_count / pageSize + 1;
                        shopAdapter.addData(shopsListByFilterModel.getShopList());
                    } else {
                        showTextToast(response.body().getMessage());
                    }
                } else {
                    showTextToast("请求失败");
                }
            }

            @Override
            public void onFailure(Call<ResponseData<ShopsListByFilterModel>> call, Throwable t) {
                ptr_shop.refreshComplete();
                isLoading = false;
                showTextToast(RequestApi.detailError(t));
            }
        });

    }

    private void loadGridData() {
        String searchParam = ed_search.getText().toString();
        String areaId = "";
        String measureArea = "";
        String priceArea = "";
        String shopType = "";
        String shopSaleType = "";
        String shopRunIndustry = "";
        String shopLabelId = "";
        String businessArea = "";
        for (int i = 0; i < AppStatus.getInstance().getList().size(); i++) {
            SearchTypeModel searchTypeModel = AppStatus.getInstance().getList().get(i);
            if ("areaId".equals(searchTypeModel.getType())) {
                if(searchTypeModel.isIs_business()){
                    businessArea= searchTypeModel.getDisplayValue();
                }else {
                    areaId = searchTypeModel.getId();
                }
            } else if ("measureArea".equals(searchTypeModel.getType())) {
                measureArea = searchTypeModel.getId();
            } else if ("priceArea".equals(searchTypeModel.getType())) {
                priceArea = searchTypeModel.getId();
            } else if ("shopType".equals(searchTypeModel.getType())) {
                shopType = searchTypeModel.getId();
            } else if ("shopSaleType".equals(searchTypeModel.getType())) {
                shopSaleType = searchTypeModel.getId();
            } else if ("shopRunIndustry".equals(searchTypeModel.getType())) {
                shopRunIndustry = searchTypeModel.getId();
            } else if ("shopLabelId".equals(searchTypeModel.getType())) {
                shopLabelId = searchTypeModel.getId();
            } else if ("businessArea".equals(searchTypeModel.getType())) {
                businessArea = searchTypeModel.getDisplayValue();
            }
        }
        Call<ResponseData<ShopsListByFilterModel>> shopsListByFilter = service.getShopsListByFilter(searchParam, areaId, measureArea, priceArea, shopType, shopSaleType, shopRunIndustry, shopLabelId, businessArea, currentPage, pageSize, AppStatus.getInstance().type);
        shopsListByFilter.enqueue(new Callback<ResponseData<ShopsListByFilterModel>>() {
            @Override
            public void onResponse(Call<ResponseData<ShopsListByFilterModel>> call, Response<ResponseData<ShopsListByFilterModel>> response) {
                ptr_shop_grid.refreshComplete();
                isLoading = false;
                if (response.body() != null) {
                    int total_count = response.body().getTotalcount();
                    int resultCode = response.body().getResultCode();
                    if (resultCode == 200) {
                        ShopsListByFilterModel shopsListByFilterModel = response.body().getData();
                        maxPage = total_count % pageSize == 0 ? total_count / pageSize : total_count / pageSize + 1;
                        shopGridAdapter.addData(shopsListByFilterModel.getShopList());
                    } else {
                        showTextToast(response.body().getMessage());
                    }
                } else {
                    showTextToast("请求失败");
                }
            }

            @Override
            public void onFailure(Call<ResponseData<ShopsListByFilterModel>> call, Throwable t) {
                ptr_shop_grid.refreshComplete();
                isLoading = false;
                showTextToast(RequestApi.detailError(t));
            }
        });

    }

    /**
     * 设置adapter
     */
    public void setAdapter() {
        shopAdapter = new ShopAdapter(R.layout.item_shop, new ArrayList<ShopListModel>());
        recy_shop.setLayoutManager(new LinearLayoutManager(getActivity()));
        recy_shop.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.divier_order_gray)));
        shopAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        recy_shop.setAdapter(shopAdapter);
    }

    public void setGridAdapter() {
        shopGridAdapter = new ShopGridAdapter(R.layout.item_grid_shop, new ArrayList<ShopListModel>());
        recy_shop_grid.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        recy_shop_grid.addItemDecoration(new DividerGridItemDecoration(getActivity(), getContext().getResources().getDrawable(R.drawable.divier_order_gray)));
        recy_shop_grid.setAdapter(shopGridAdapter);
    }

    private void setAreaAdapter() {
        areaAdapter = new SignlLineAdapter(R.layout.item_signal_line, new ArrayList<SearchTypeModel>());
        recy_area.setLayoutManager(new LinearLayoutManager(getActivity()));
        recy_area.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.divier_order_gray_1)));
        recy_area.setAdapter(areaAdapter);
        List<SearchTypeModel> list = new ArrayList<>();
        for (int i = 0; i < shopsSearchModel.getAreaList().size(); i++) {
            AreaListModel areaListModel = shopsSearchModel.getAreaList().get(i);
            SearchTypeModel model = new SearchTypeModel(areaListModel.getName(), areaListModel.getCode(), "areaId");
            list.add(model);
        }
        areaAdapter.setNewData(list);
    }

    private void setMeasureAdapter() {
        measureAdapter = new SignlLineAdapter(R.layout.item_signal_line, new ArrayList<SearchTypeModel>());
        recy_measure.setLayoutManager(new LinearLayoutManager(getActivity()));
        recy_measure.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.divier_order_gray_1)));
        recy_measure.setAdapter(measureAdapter);
        List<SearchTypeModel> list = new ArrayList<>();
        for (int i = 0; i < shopsSearchModel.getMeasureAreaList().size(); i++) {
            MeasureAreaListModel measureAreaListModel = shopsSearchModel.getMeasureAreaList().get(i);
            SearchTypeModel model = new SearchTypeModel(measureAreaListModel.getMeasureDisplayName(), measureAreaListModel.getMeasureValue(), "measureArea");
            list.add(model);
        }
        measureAdapter.setNewData(list);
    }

    private void setPriceAdapter() {
        priceAdapter = new SignlLineAdapter(R.layout.item_signal_line, new ArrayList<SearchTypeModel>());
        recy_price.setLayoutManager(new LinearLayoutManager(getActivity()));
        recy_price.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.divier_order_gray_1)));
        recy_price.setAdapter(priceAdapter);
        List<SearchTypeModel> list = new ArrayList<>();
        for (int i = 0; i < shopsSearchModel.getPriceAreaList().size(); i++) {
            PriceAreaListModel priceAreaListModel = shopsSearchModel.getPriceAreaList().get(i);
            SearchTypeModel model = new SearchTypeModel(priceAreaListModel.getPriceDisplayName(), priceAreaListModel.getPriceValue(), "priceArea");
            list.add(model);
        }
        priceAdapter.setNewData(list);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    private void setDialog(LinearLayout lin, ImageView iv, TextView tv, boolean isShow) {
        TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                -1.0f);
        mHiddenAction.setDuration(200);
        TranslateAnimation mShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        mShowAction.setDuration(300);

        lin_diag_area.setVisibility(View.GONE);
        lin_dialog_measure.setVisibility(View.GONE);
        lin_dialog_price.setVisibility(View.GONE);
        tv_area.setTextColor(getResources().getColor(R.color.grey));
        tv_measure.setTextColor(getResources().getColor(R.color.grey));
        tv_price.setTextColor(getResources().getColor(R.color.grey));
        Glide.with(this).load(R.drawable.img_down).placeholder(R.drawable.img_down).into(img_area);
        Glide.with(this).load(R.drawable.img_down).placeholder(R.drawable.img_down).into(img_measure);
        Glide.with(this).load(R.drawable.img_down).placeholder(R.drawable.img_down).into(img_price);

        if (isShow) {
            lin.startAnimation(mShowAction);
            lin.setVisibility(View.VISIBLE);
            Glide.with(this).load(R.drawable.img_up).crossFade().placeholder(R.drawable.img_up).into(iv);
            tv.setTextColor(getResources().getColor(R.color.purple));
        }

    }

    private void reset() {
        lin_diag_area.setVisibility(View.GONE);
        lin_dialog_measure.setVisibility(View.GONE);
        lin_dialog_price.setVisibility(View.GONE);
        tv_area.setTextColor(getResources().getColor(R.color.grey));
        tv_measure.setTextColor(getResources().getColor(R.color.grey));
        tv_price.setTextColor(getResources().getColor(R.color.grey));
        Glide.with(this).load(R.drawable.img_down).placeholder(R.drawable.img_down).into(img_area);
        Glide.with(this).load(R.drawable.img_down).placeholder(R.drawable.img_down).into(img_measure);
        Glide.with(this).load(R.drawable.img_down).placeholder(R.drawable.img_down).into(img_price);
        area_select = false;
        measure_select = false;
        price_select = false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rel_left:
                List<CityModel> cityList=AppStatus.getCityList();
                final PopupMenu popupMenu = new PopupMenu(getActivity(), v);
                for (int i = 0; i < cityList.size(); i++) {
                    popupMenu.getMenu().add(0, i, 0, cityList.get(i).getCityName()).setTitleCondensed(String.valueOf(cityList.get(i).getCityId()));
                }
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        String productName = item.getTitle().toString();
                        tv_left.setText(productName);
                        AppStatus.getInstance().cityName=productName;
                        return true;
                    }
                });
                popupMenu.show();
                break;
            case R.id.tv_busniss_left:
                tv_busniss_left.setTextColor(getResources().getColor(R.color.purple));
                tv_area_left.setTextColor(getResources().getColor(R.color.grey));
                List<SearchTypeModel> lists = new ArrayList<>();
                for (int i = 0; i < shopsSearchModel.getBusinessAreaList().size(); i++) {
                    BusinessAreaListModel businessAreaListModel = shopsSearchModel.getBusinessAreaList().get(i);
                    SearchTypeModel model = new SearchTypeModel(businessAreaListModel.getName(), businessAreaListModel.getCode(), "areaId");
                    model.setIs_business(true);
                    lists.add(model);
                }
                areaAdapter.setNewData(lists);
                break;
            case R.id.tv_area_left:
                tv_busniss_left.setTextColor(getResources().getColor(R.color.grey));
                tv_area_left.setTextColor(getResources().getColor(R.color.purple));
                List<SearchTypeModel> list = new ArrayList<>();
                for (int i = 0; i < shopsSearchModel.getAreaList().size(); i++) {
                    AreaListModel areaListModel = shopsSearchModel.getAreaList().get(i);
                    SearchTypeModel model = new SearchTypeModel(areaListModel.getName(), areaListModel.getCode(), "areaId");
                    model.setIs_business(false);
                    list.add(model);
                }
                areaAdapter.setNewData(list);
                break;
            case R.id.lin_screen:
                Bundle bundle = new Bundle();
                bundle.putSerializable("shopsSearchModel", shopsSearchModel);
                startActivityForResult(ScreenActivity.class, bundle, 101);
                // startActivity(MapActivity.class);
                break;
            case R.id.rel_right:
                if ("list".equals(show_type)) {
                    show_type = "grid";
                    ptr_shop_grid.setVisibility(View.VISIBLE);
                    ptr_shop.setVisibility(View.GONE);
                    ptr_shop_grid.postDelayed(
                            new Runnable() {
                                @Override
                                public void run() {
                                    ptr_shop_grid.autoRefresh();
                                }
                            }, 100);
                } else {
                    show_type = "list";
                    ptr_shop_grid.setVisibility(View.GONE);
                    ptr_shop.setVisibility(View.VISIBLE);
                    ptr_shop.postDelayed(
                            new Runnable() {
                                @Override
                                public void run() {
                                    ptr_shop.autoRefresh();
                                }
                            }, 100);
                }

                break;
            case R.id.rel_area:
                if (shopsSearchModel != null) {
                    if (area_select) {
                        area_select = false;
                        setDialog(lin_diag_area, img_area, tv_area, false);
                    } else {
                        reset();
                        area_select = true;
                        setDialog(lin_diag_area, img_area, tv_area, true);
                    }
                } else {
                    showTextToast("数据异常，请稍候再试");
                    setSelectData();
                }
                break;
            case R.id.rel_measure:
                if (shopsSearchModel != null) {
                    if (measure_select) {
                        measure_select = false;
                        setDialog(lin_dialog_measure, img_measure, tv_measure, false);
                    } else {
                        reset();
                        measure_select = true;
                        setDialog(lin_dialog_measure, img_measure, tv_measure, true);
                    }
                } else {
                    showTextToast("数据异常，请稍候再试");
                    setSelectData();
                }
                break;
            case R.id.rel_price:
                if (shopsSearchModel != null) {
                    if (price_select) {
                        price_select = false;
                        setDialog(lin_dialog_price, img_price, tv_price, false);
                    } else {
                        reset();
                        price_select = true;
                        setDialog(lin_dialog_price, img_price, tv_price, true);
                    }
                } else {
                    showTextToast("数据异常，请稍候再试");
                    setSelectData();
                }
                break;

        }
    }
}
